package com.ssish.saas.eccs.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.joda.time.Days;
import org.joda.time.Months;
import org.joda.time.Weeks;
import org.joda.time.Years;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


public class DateUtils {
    final static public String DATE_TIME_FORMAT_YMD = "yyyy-MM-dd";
    final static public String DATE_TIME_FORMAT_YMDMMDD = "yyyy-MM-dd HH:mm:ss";
    final static public String DATE_TIME_FORMAT = "yyyyMMddHHmmss";
    final static public String DATE_TIME_FORMAT_DDMMYYYY = "dd/MM/yyyy";

    final static public long millsOneSecond = 1000;
    final static public long millsOneMinute = 60 * millsOneSecond;
    final static public long millsOneHour = 60 * millsOneMinute;
    final static public long millsOneDay = 24 * millsOneHour;

    public static Date fromatDate(String pre,String date) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat(pre);
        return sdf.parse(date);
    }


    public static String fromatDateStr(String date, String pattern) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date d = sdf.parse(date);
        return sdf.format(d);
    }

    /**
     * <p>Title: differentDays</p>
     * <p>Description: 计算两个日期的天数</p>
     * @param smdate 前一个日期
     * @param bdate  后一个日期
     * @param formatter 日期格式 yyyy-MM-dd
     * @return
     * @throws ParseException
     * @author 朱剑  2017年11月27日 下午2:31:12
     */
    public static int differentDays(String smdate,String bdate,String formatter) throws ParseException {
        DateTimeFormatter dfter = DateTimeFormat.forPattern(formatter);
        Days  days= Days.daysBetween(dfter.parseDateTime(smdate), dfter.parseDateTime(bdate));
        return days.getDays();
    }


    public static int intevalDays(Date startDate, int startDateHour, Date endDate, int endDateHour) throws Exception {
        long diffTime = (endDate.getTime() + endDateHour * millsOneHour) - (startDate.getTime() + startDateHour * millsOneHour);
        int diffDay = (int)(diffTime/millsOneDay);
//		long diffT = diffTime - diffDay * millsOneDay;
//		if(diffT > 0){
//			diffDay ++;
//		}else if(diffT < 0){
//			diffDay --;
//		}
        return diffDay;

    }

    /**
     * <p>Title: differentWeeks</p>
     * <p>Description: 计算两个日期之间的星期，不满一周按照一周来算</p>
     * @param smdate
     * @param bdate
     * @param formatter
     * @return
     * @throws ParseException
     * @author 朱剑  2017年11月27日 下午3:56:40
     */
    public static int differentWeeks(String smdate,String bdate,String formatter) throws ParseException {
        DateTimeFormatter dfter = DateTimeFormat.forPattern(formatter);
        Weeks  weeks= Weeks.weeksBetween(dfter.parseDateTime(smdate), dfter.parseDateTime(bdate));
        return weeks.getWeeks();
    }
    /**
     * <p>Title: differentMonths</p>
     * <p>Description: 计算2个时间的月份，未满一个月，按照一个月计算</p>
     * @param smdate
     * @param bdate
     * @param formatter
     * @return
     * @throws ParseException
     * @author 朱剑  2017年11月27日 下午2:36:56
     */
    public static int differentMonths(String smdate,String bdate,String formatter) throws ParseException {
        DateTimeFormatter dfter = DateTimeFormat.forPattern(formatter);
        Months  months= Months.monthsBetween(dfter.parseDateTime(smdate), dfter.parseDateTime(bdate));
        return months.getMonths()+1;
    }


    public static int getMonthMinus(Date startDate, int startDateHour, Date endDate, int endDateHour) throws Exception{
        int months = 0;
        Calendar start = Calendar.getInstance();
        start.setTime(startDate);
        Calendar end = Calendar.getInstance();
        end.setTime(endDate);
        months = (end.get(Calendar.YEAR) - start.get(Calendar.YEAR)) *12
                + end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
        if(end.get(Calendar.DATE) - start.get(Calendar.DATE) >0
                || (end.get(Calendar.DATE) == start.get(Calendar.DATE) && endDateHour > startDateHour)){
            months ++;
        }
        return months;
    }


    /**
     * <p>Title: differentYears</p>
     * <p>Description: 计算2个日期之间的年，未满一年按1年计算</p>
     * @param smdate
     * @param bdate
     * @param formatter
     * @return
     * @throws ParseException
     * @author 朱剑  2017年11月27日 下午2:39:05
     */
    public static int differentYears(String smdate,String bdate,String formatter) throws ParseException {
        DateTimeFormatter dfter = DateTimeFormat.forPattern(formatter);
        Years  years= Years.yearsBetween(dfter.parseDateTime(smdate), dfter.parseDateTime(bdate));
        return years.getYears();
    }

    public static Date parse(String date,String pattern){
        DateFormat fmt = new SimpleDateFormat(pattern);
        try {
            return fmt.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     *
     * <p>Title: format</p>
     * <p>Description: TODO</p>
     * @param date
     * @param pattern
     * @return
     * @author jie.xu  2018年1月3日 上午11:23:29
     */
    public static String format(Date date,String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }


    public static String formatDateByNum(Date date, String pattern, int num, String type){
        SimpleDateFormat sf = new SimpleDateFormat(pattern);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        if("Y".equals(type)){
            calendar.add(calendar.YEAR,num);
        }else if("M".equals(type)){
            calendar.add(calendar.MONTH,num);
        }else if("D".equals(type)){
            calendar.add(calendar.DATE,num);
        }
        date = calendar.getTime();
        return sf.format(date);
    }

    public static String formatDateByTypeNum(String date, String pattern, int num, String type) throws ParseException{
        Date d1 = fromatDate(DATE_TIME_FORMAT_YMD, date);
        SimpleDateFormat sf = new SimpleDateFormat(pattern);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(d1);
        if("Y".equals(type)){
            calendar.add(calendar.YEAR,num);
            calendar.add(calendar.DATE,-1);
        }else if("M".equals(type)){
            calendar.add(calendar.MONTH,num);
        }else if("D".equals(type)){
            calendar.add(calendar.DATE,num-1);
        }
        d1 = calendar.getTime();
        return sf.format(d1);
    }

    public static int compareDate(String date1, String date2){
        try {
            Date d1 = fromatDate(DATE_TIME_FORMAT_YMD, date1);
            Date d2 = fromatDate(DATE_TIME_FORMAT_YMD, date2);
            return d1.compareTo(d2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }


    //由出生日期获得年龄
    public static int getAge(String birth, String date) throws Exception {
        Date birthDay = parse(birth, DATE_TIME_FORMAT_YMD);
        Calendar cal = Calendar.getInstance();
        cal.setTime(birthDay);

        Calendar cal2 = Calendar.getInstance();
        if(!"".equals(date)){
            Date compareDate = parse(date, DATE_TIME_FORMAT_YMD);
            cal2.setTime(compareDate);
        }
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal2.get(Calendar.YEAR);
        int monthNow = cal2.get(Calendar.MONTH);
        int dayOfMonthNow = cal2.get(Calendar.DAY_OF_MONTH);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }
    /**
     * 日期参数相加
     * @param date
     * @param day
     * @return
     */
    public static Date addDate(Date date, long day) {
        long time = date.getTime(); // 得到指定日期的毫秒数
        day = day*24*60*60*1000; // 要加上的天数转换成毫秒数
        time+=day; // 相加得到新的毫秒数
        return new Date(time); // 将毫秒数转换成日期
    }

    /**
     * 根据生日获取年龄
     * @param birthday
     * @return
     * @throws Exception
     */
    public static  int getAgeByBirth(Date birthday) throws Exception {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间
            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);
            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }
}
